package com.nifostasky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nifostasky.constant.CacheConstant;
import com.nifostasky.dao.UserDao;
import com.nifostasky.entity.User;
import com.nifostasky.service.UserService;
import com.nifostasky.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;


/**
 * 用户表(User)表服务实现类  工具类形式
 *
 * @author makejava
 * @since 2021-09-26 11:08:49
 */
@Service("userUtilService")
@RequiredArgsConstructor
public class UserUtilServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    private final RedisUtil redisUtil;

    String allKey = CacheConstant.getRoleCacheKey("all");

    /**
     * 查询全部
     * @return
     */
    @Override
    public List<User> queryAll() {
        //先查询redis缓存,看是否有用户信息,如果存在,则直接返回缓存信息;
        List<User> redisUsers = redisUtil.getCacheList(allKey);
        if (!CollectionUtils.isEmpty(redisUsers)){
            return redisUsers;
        }
        //不存在,则真正查询数据库
        List<User> users = baseMapper.selectList(new QueryWrapper<User>());

        //返回值,如果存在数据,则存redis;
        if (CollectionUtils.isEmpty(users)){
            return null;
        }
        redisUtil.setCacheList(allKey,users);
        return users;
    }

    /**
     * 根据id查询用户
     * @param userId
     * @return
     */
    @Override
    public User getUserInfo(Long userId) {
        //先查询redis
        String userCacheKey = CacheConstant.getRoleCacheKey(String.valueOf(userId));
        User redisUser = redisUtil.getCacheObject(userCacheKey);

        if(Objects.nonNull(redisUser)) {
            return redisUser;
        }
        //不存在则真实查询数据库
        User user = baseMapper.selectById(userId);

        if(Objects.isNull(user)) {
            return null;
        }
        redisUtil.setCacheObject(userCacheKey, user);
        return user;
    }

    /**
     * 增加用户
     * @param user
     */
    @Override
    public void add(User user) {
        baseMapper.insert(user);
        redisUtil.deleteObject(allKey);
    }

    /**
     * 更新用户
     * @param user
     */
    @Override
    public void update(User user) {
        if (Objects.isNull(user) || Objects.isNull(user.getId())){
            return;
        }
        String userCacheKey = CacheConstant.getRoleCacheKey(String.valueOf(user.getId()));
        baseMapper.updateById(user);
        // 更新缓存
        redisUtil.setCacheObject(userCacheKey,user);
        // 清除缓存
        redisUtil.deleteObject(allKey);
    }

    /**
     * 删除用户
     * @param userId
     */
    @Override
    public void delete(Long userId) {
        baseMapper.deleteById(userId);
        // 清除缓存
        redisUtil.deleteObject(CacheConstant.getRoleCacheKey(String.valueOf(userId)));
        redisUtil.deleteObject(allKey);
    }
}
